using System.Linq;
using System.Reflection;
using Game.Framework;
using Game.Framework.Utils;
using HybridCLR;
using UnityEngine;

public class DllLoader
{
    private const string RootPath = "Assets/AssetsPackage/HotUpdate";
    
    public static string[] dlls = new[]
    {
        "Framework.Runtime",
    };
    
    public static void LoadHotUpdateDlls()
    {
        for (var i = 0; i < dlls.Length; i++) LoadDll(dlls[i]);
#if !UNITY_EDITOR
        LoadMetadataForAOTAssemblies();
#endif
    }
    
    public static Assembly LoadDll(string dllName)
    {
        Debug.Log($"Load dll:{dllName}");
        if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.LinuxEditor)
        {
            return System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == dllName);
        }
    
        var hander = YooAssetManager.Instance.Package.LoadAssetSync<TextAsset>($"{RootPath}/{dllName}");
        TextAsset txt = hander.AssetObject as TextAsset;
        var assembly = Assembly.Load(txt.bytes);
        return assembly;
    }
    
    private static void LoadMetadataForAOTAssemblies()
    {
        foreach (var aotDllName in AOTGenericReferences.PatchedAOTAssemblyList)
        {
            var dllName = aotDllName.Replace(".dll", "");
            var hander = YooAssetManager.Instance.Package.LoadAssetSync<TextAsset>($"{RootPath}/{dllName}");
            TextAsset txt = hander.AssetObject as TextAsset;
            var err = RuntimeApi.LoadMetadataForAOTAssembly(txt.bytes, HomologousImageMode.SuperSet);
            if (err != LoadImageErrorCode.OK)
            {
                LogUtil.LogError($"LoadMetadataForAOTAssembly:{dllName}. ret:{err}");
            }
            else
            {
                LogUtil.Log($"LoadMetadataForAOTAssembly:{dllName}. ret:{err}");
            }
        }
    }
    
    public static void UnloadDllTextRes()
    {
        if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.LinuxEditor)
        {
            return;
        }
        YooAssetManager.Instance.Package.UnloadAllAssetsAsync();
    }
}
